Online-Academy
Look, Read, Understand, Apply

Data Analytics

Decision Tree - Classification

import pandas as pd
from sklearn.tree import DecisionTreeClassifier, plot_tree
import matplotlib.pyplot as plt

# 1. Prepare the historical dataset
# Mapping:
# Outlook: Sunny = 0, Rainy = 1
# Temperature: Hot = 0, Mild = 1, Cool = 2
# Windy: No = 0, Yes = 1
data = {
    'Outlook': [0, 1, 0, 0, 1],
    'Temperature': [0, 1, 1, 0, 2],
    'Windy': [0, 1, 0, 1, 0],
    'Activity': ['Beach', 'Home', 'Beach', 'Home', 'Home']
}

df = pd.DataFrame(data)

# Separate features (X) and target label (y)
X = df[['Outlook', 'Temperature', 'Windy']]
y = df['Activity']

# 2. Initialize and train the Decision Tree Classifier
# We use 'entropy' or 'gini' to select the best splits
model = DecisionTreeClassifier(criterion='entropy', random_state=42)
model.fit(X, y)

# 3. Predict the activity for a new weekend scenario
# New Data: Outlook = Sunny (0), Temperature = Mild (1), Windy = No (0)
new_weekend = [[0, 1, 0]]
prediction = model.predict(new_weekend)

print(f"Prediction for the new weekend: {prediction[0]}")

# 4. Optional: Visualize the trained tree structure
plt.figure(figsize=(6,6))
plot_tree(model, feature_names=X.columns, class_names=model.classes_, filled=True)
plt.show()